import React, { useState,useEffect, useTransition,useRef  } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select, Tabs,Tooltip,List,Table,Tree } from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined,SearchOutlined,FileOutlined  } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { listFunction,getFunction,delFunction,addFunction,updateFunction} from "@/api/modules/jnj/safetyFunction";
import { listCategory,getCategory,delCategory,addCategory,updateCategory,batchLink} from "@/api/modules/jnj/safetyCategory";
import { ProFormColumnsType } from '@ant-design/pro-components'
import { getInfo } from "@/api/login/ssoLogin";

const {TextArea} = Input;
const { Option } = Select;
const { TabPane } = Tabs; 

const rmfunction = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [isModalVisible2, setIsModalVisible2] = useState(false); 
  const [Title2, setTitle2] = useState("")  
  const [form2] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [isView2, SetisView2] = useState(false)
  const [riskdistances,setRiskdistances] = useState([]); 
  const [onReloadNum, setReloadNum] = useState(0); 
  const [onReloadNum2, setReloadNum2] = useState(0); 
  const [peoplelist,setPeople] = useState([])
  const [tab1Data,setTab1Data] = useState([])
  const [isTreeModalVisible,setIsTreeModalVisible] = useState(false)
  const [newtreeData,setTreedata] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([]); // 用于保存勾选的节点key 
  const [checkIds, setcheckIds] = useState([]); // 用于保存勾选的节点keyid
  const [selectId, setSelectId] = useState(null); // 用于保存下拉框

   // 搜索框的状态  
 const [name, setIngredient] = useState(''); 
 const [description, setDescription] = useState(''); 
 const [viewStatus, setViewStatus] = useState(false); // 加载状态 


 useEffect(()=>{
  getInfo().then(res=>{
    console.log(res,'res')
    const data = res.data
    data.roles.forEach((item)=>{
      if(item == "Formulator"){
        setViewStatus(true)
      }
    })
  }) 
  let query ={pageNum:1,pageSize:10}
  getData2(query)
 },[])

  const formColumns:ProFormColumnsType[] = [ {
    title: t('function.name'),
    dataIndex: 'name',
    valueType: 'text', 
  },{
    title: t('function.decription'),
    dataIndex: 'decription',
    valueType: 'text', 
  }
    
  ]

  const columns: any = [
    {
      title: t('function.name'),
      dataIndex: 'name',
      key: 'name',
      width: 150,
      fixed:'left',
    },
    {
      title: t('function.decription'),
      dataIndex: 'decription',
      key: 'decription',
      ellipsis: {
        showTitle: false,
      },
      render: (decription) => (
        <Tooltip placement="topLeft" title={decription}>
          {decription}
        </Tooltip>
      ),
    },
    {
      title: t('function.children'),
      dataIndex: 'children1',
      key: 'children1',
      ellipsis: {
        showTitle: false,
      },
      render: (children1) => (
        <Tooltip placement="topLeft" title={children1}>
          {children1}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
         <Button type="link" onClick={() => handleView(record)}>  
          {t('view')}  
          </Button>  
          {/* <Button type="link" onClick={() => handleEdit(record)}>  
          {t('edit')}  
          </Button>   */}
          {/* <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>  
    */}
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await listFunction({...formData,orderByColumn:'id',isAsc:'desc', order: 0})
    if(!success) return false
    let list = data.rows
    list.map(i=>{
      i.children1 = i.children
      delete i.children
    })
    return {
      data: list,
      total: data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue(); 
    
    if(Title=='修改/Edit'){
      values.children = values.children1
      updateFunction(values).then(response => {
        message.success("success")
        setIsModalVisible(false);
        setReloadNum(onReloadNum+1)
       }).catch(()=>{
        message.error("error")
       });  
      }else{
        values.children = values.children1
          addFunction(values).then(response => {
          message.success("success")
          setIsModalVisible(false);
          setReloadNum(onReloadNum+1)
         }).catch(()=>{
          message.error("error")
         });
      }

    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView = (record) =>{
   SetisView(true)
   setTitle("查看/View")
   console.log(record,'record')
   form.setFieldsValue({ ...record });  
   setIsModalVisible(true);  
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delFunction(inciIds).then(res=>{
            message.success("Success")
            setReloadNum(onReloadNum+1)
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  //select查询

  const [searchResult, setSearchResult] = useState([]);  
  const [visible, setVisible] = useState(false);  
  const [selectedResult, setSelectedResult] = useState(null);  
  
  const handleSelectResult = (result) => {  
    form.setFieldsValue({ inciStr: result.name }); // 回填表单  
    form.setFieldsValue({lawInciSerial:result.serial})
    setSelectedResult(result);  
    setVisible(false); // 关闭弹窗  
  };  
  
  const modalFooter = [  
    <Button key="back" onClick={() => setVisible(false)}>  
      取消  
    </Button>,  
    <Button key="submit" type="primary" onClick={() => handleSelectResult(selectedResult)}>  
      选择  
    </Button>,  
  ];  

  //风险物质列表

  
  const formColumns2:ProFormColumnsType[] = [
    {
      title: t('function.name'),
      dataIndex: 'name',
      valueType: 'text', 
    },{
      title: t('function.decription'),
      dataIndex: 'decription',
      valueType: 'text', 
    }
  ]

  const columns2: any = [
    {
      title: t('function.name'),
      dataIndex: 'name',
      key: 'name',
      width: 120,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (name) => (
        <Tooltip placement="topLeft" title={name}>
          {name}
        </Tooltip>
      ),
    },
    {
      title: t('function.decription'),
      dataIndex: 'decription',
      key: 'decription',
      width: 120,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (decription) => (
        <Tooltip placement="topLeft" title={decription}>
          {decription}
        </Tooltip>
      ),
    },
    {
      title: t('function.seq'),
      dataIndex: 'seq',
      key: 'seq',
      width: 120,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (seq) => (
        <Tooltip placement="topLeft" title={seq}>
          {seq}
        </Tooltip>
      ),
    },
    {
      title: t('remark'),
      dataIndex: 'remark',
      key: 'remark',
      width: 120,
      fixed:'left',
      ellipsis: {
        showTitle: false,
      },
      render: (remark) => (
        <Tooltip placement="topLeft" title={remark}>
          {remark}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView2(record)}>  
           {t('view')}  
          </Button> 
          {/* <Button type="link" onClick={() => handleEdit2(record)}>  
          {t('edit')}  
          </Button>   */}
          {/* <Button type="link" danger onClick={() => handleDelete2(record.id)}>  
          {t('delete')}   
          </Button>   */}
   
        </>  
      ),  
    },  
  ];


  const getData2 = async (formData) => {
    const { success, data} = await listCategory({...formData, orderby: 'id',orderByColumn:'id', order: 0})
    if(!success) return false
    console.log(data)
    let list2 = data.rows
    list2.map(i=>{
      i.key=i.id
    })
    setTab1Data(list2)
    return {
      data: list2,
      total: data.total
    }
  } 

  const handleBind = () =>{
    AllItem()
    setCheckedKeys([])
    setSelectId(null)
    setIsTreeModalVisible(true)
  }
  
  const handleOkTree = () =>{
    if(checkIds.length>0){
      checkIds.map(k=>{
        let form={id:k,safetyFunctionCategoryId:selectId}
        updateFunction(form).then(res=>{
          if(res.data.code==200){
            message.success("success")
            setIsTreeModalVisible(false)
            fetchData2(1,10,'','')
          }
        })
      })
    }
   
  }

  const AllItem = () =>{
    let query={pageNum:1,pageSize:9999}
    let treeData = []
    listCategory(query).then(res=>{
     console.log(res.data.rows,'treea')
     let treeId=[];
     let rawTreeData=res.data.rows;
     rawTreeData.map(item=>{
       treeData.push({
         id:item.id,
         key:item.name+item.id,
         title:item.name,
         label:item.name,
         button:false,
         children:[]
       })
     })
     treeData.map(item=>{
       rawTreeData.map(i=>{
         i.safetyFunctionList.map(k=>{
           if(k.safetyFunctionCategoryId == item.id){
             item.children.push({
               id:k.id,
               key:k.name+k.id,
               label:k.name,
               title:k.name,
               button:true,
             })
           }
         })
       })
     })
     setTreedata(treeData)
     console.log(treeData,'newtree')
   })
 }

  const handleAdd2 = () =>{
    SetisView2(false)
    form2.resetFields()
    setTitle2("新增/New")
    showModal2()
  }

  const showModal2 = () => {  
    setIsModalVisible2(true);  
  };  

  
  const handleOk2 = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form2.getFieldsValue(); 
    if(Title2=='新增/New'){
        //新增
        values.id =null
        addCategory(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false); 
            fetchData2(1,10,'','') 
        }).catch(()=>{
           
        })
    }else{
        //修改
        updateCategory(values).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
             // 假设添加成功，关闭弹窗  
            setIsModalVisible2(false);  
            fetchData2(1,10,'','') 
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView2 = (record) =>{
   SetisView2(true)
   setTitle2("查看/View")
   console.log(record,'record')
   form2.setFieldsValue({ ...record });  
   setIsModalVisible2(true);  
  }

  const handleEdit2 = (record) =>{
    SetisView2(false)
    setTitle2("修改/Edit")
    console.log(record,'record')
    form2.setFieldsValue({ ...record });  
    setIsModalVisible2(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete2 = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        delCategory(inciIds).then(res=>{
            message.success("Success")
            setReloadNum2(onReloadNum2+1)
            fetchData2(1,10,'','') 
        }) 
      },  
    }); 
  }
  
  const handleCancel2 = () => {  
    setIsModalVisible2(false);  
  };  

  const expandedRowRender = (record) => {  
    // 如果record有subData属性，则渲染子表格  
    if (record.safetyFunctionList && record.safetyFunctionList.length > 0) {  
      // 使用subData作为子表格的数据源  
      return(
        <div style={{marginLeft:'5%'}}>
          {record.safetyFunctionList.map((item,index)=>(
            <div key={index}>  
            {/* 在 name 前面放置一个图标 */}  
            <FileOutlined/> {item.name}  
          </div>  
          ))}
        </div>
      )
    }  
    return null; // 如果没有子数据，则不渲染内容  
  };  

 // 重置函数  
 const handleReset = () => {  
      setIngredient(''); // 清空搜索框  
      // 可能还需要将 currentPage 重置为 1，取决于你的需求  
      // setCurrentPage(1);  
      setDescription('');
      fetchData2(1,50,'','')
    };  
  
  // 搜索函数  
  const handleSearch2 = () => {  
    fetchData2(1,50,name,description)
  };  
  const fetchData2 = async (currentPage,pageSize,name,description) => {
    const param = {pageNum:currentPage,pageSize:pageSize,name:name,decription:description,orderByColumn:'id',}
    const { success, data} = await listCategory(param)
    if(!success) return false
    console.log(data)
    let list2 = data.rows
    list2.map(i=>{
      i.key=i.id
    })
    setTab1Data(list2)
    return {
      data: list2,
      total: data.total
    }
  } 
  
  const onCheck = (checkedKeysValue) => { 
    let checkId = []
    if(checkedKeysValue.length>0){
      checkedKeysValue.map(i=>{
        newtreeData.map(k=>{
          k.children.map(o=>{
            if(i==o.key){
              checkId.push(o.id)
            }
          })
        })
      })
      setcheckIds(checkId); // 更新状态以保存勾选的节点key  
      setCheckedKeys(checkedKeysValue)
    }else{
      setcheckIds(checkedKeysValue);
      setCheckedKeys(checkedKeysValue)
    }
   
  };  
  const handleSelectChange = (value) => {  
    setSelectId(value);  
  };  

  const renderOperator = <>
    <Button type="primary" size="small" disabled={viewStatus} onClick={handleAdd}>{t('add')}</Button>
  </>
    // 自定义是否可展开的函数  
    const rowExpandable = (record) => record.name !== 'Not Expandable';  
  return (
    <div> 
      <Card>
      <Tabs type="card" defaultActiveKey="原料功能">  
        <TabPane tab={t('RMFunction')} key="原料功能">  
          <MemoTable 
            name='rmfunction'
            formColumns={formColumns}
            columns={columns as any}
            rowKey='id'
            operator={renderOperator}
            getData={getData}
            refreshKey={onReloadNum}
          /> 
        </TabPane>  
        <TabPane tab={t('RMCategory')} key="原料大类">
        <Card className="box-card" style={{ marginBottom: 24, minWidth: '700px' }}>  
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>  
  <div style={{ marginRight: '20px' }}>  
    <div style={{ fontWeight: 'bold' }}>{t('name')}</div>  
    <Input style={{ width: '240px' }} value={name} onChange={(e) => setIngredient(e.target.value)} />  
  </div>  
  <div>  
    <div style={{ fontWeight: 'bold', marginRight: '10px' }}>{t('function.decription')}</div>  
    <Input style={{ width: '240px' }} value={description} onChange={(e) => setDescription(e.target.value)} />  
  </div>  
  <div style={{ display: 'flex', alignItems: 'center', marginLeft: 'auto' }}>  
    <Button onClick={handleReset} size='small' style={{ marginRight: '8px' }}>{t('cancel')}</Button>  
    <Button type="primary" size='small' onClick={handleSearch2}>{t('search')}</Button>  
  </div>  
</div>
      </Card> 
      <Button size='small' disabled={viewStatus} style={{marginBottom:'2%'}} type="primary" onClick={handleAdd2}>  
          {t('add')}  
        </Button> 
        <Button size='small' disabled={viewStatus} style={{marginBottom:'2%',marginLeft:'1%'}} type="primary" onClick={handleBind}>
        {t('bind')} 
        </Button>
        <Table  
          dataSource={tab1Data}  
          columns={columns2} 
          expandable={{  
            expandedRowRender,  
            rowExpandable,  
          }}  
        />    
        </TabPane>  
      </Tabs> 
      </Card>
       

    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}   
            <Form.Item  
              name="name"  
              label={t('function.name')} 
              rules={[{ required: true, message: '请输入名称！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="decription"  
              label={t('function.decription')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item> 
            <Form.Item  
              name="children1"  
              label={t('function.children')}  
            >  
              <Select disabled={isView}>
                <Option value="Y">Y</Option>  
                <Option value="N">N</Option>  
              </Select>  
            </Form.Item> 
          </Form>  
        </Modal>  
        <Modal  
          title={Title2}
          visible={isModalVisible2}  
          onOk={handleOk2}  
          onCancel={handleCancel2}  
        >  
          <Form form={form2} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="name"  
              label={t('function.name')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item>  
            <Form.Item  
              name="decription"  
              label={t('function.decription')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item>  
            <Form.Item  
              name="seq"  
              label={t('function.seq')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
            <Form.Item  
              name="remark"  
              label={t('remark')}
            >  
              <Input disabled={isView2}/>  
            </Form.Item> 
          </Form>  
        </Modal> 
        <Modal  
        title="Function & Category"  
        visible={isTreeModalVisible}  
        onOk={handleOkTree}  
        onCancel={()=>setIsTreeModalVisible(false)}  
        width={800} // 根据需要设置宽度  
        destroyOnClose
      >  
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>  
          <div style={{ width: '50%', padding: '20px' }}>  
            <h3>Function</h3>  
            <Tree defaultExpandParent treeData={newtreeData}  checkable onCheck={onCheck} checkedKeys={checkedKeys} />  
          </div>  
          <div style={{ width: '45%', padding: '20px' }}>  
            <h3>Category</h3>  
            <Select  
              style={{ width: 300 }}  
              placeholder="Please select"  
              value={selectId}  
              onChange={handleSelectChange}  
            >  
              {tab1Data.map((item) => (  
                <Select.Option key={item.id} value={item.id}>  
                  {item.name}  
                </Select.Option>  
              ))}  
            </Select>  
          </div>  
        </div>  
      </Modal>  
    </div>
  )
}
export default rmfunction
